package com.h6.crm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.h6.crm.entity.Attachment;
import com.h6.crm.service.AttachmentService;
import com.h6.crm.util.pojo.R;
import com.h6.crm.util.pojo.vo.UploadFileVO;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;

@Tag(name = "附件管理", description = "附件管理的API")
@RestController
@RequestMapping("/attachment")
public class AttachmentController {

    @Autowired
    AttachmentService attachmentService;

    @Operation(summary = "上传附件")
    @ApiResponses({
            @ApiResponse(responseCode = "200", content = {
                    @Content(mediaType = "application/octet-stream") }) })
    @PostMapping("/upload")
    public Attachment fileUpload(@Valid @ModelAttribute UploadFileVO fileVO) {
        return attachmentService.uploadAttachment(fileVO);
    }

    @Operation(summary = "下载附件")
    @ApiResponses({
            @ApiResponse(responseCode = "200", content = {
                    @Content(mediaType = "application/octet-stream") }) })
    @PostMapping("/download/{fileId}")
    public void fileDownLoad(HttpServletResponse response, @PathVariable("fileId") Long fileId) {
        attachmentService.downloadAttachment(response, fileId);
    }

    @Operation(summary = "删除附件")
    @ApiResponses({
            @ApiResponse(responseCode = "200", content = {
                    @Content(schema = @Schema(implementation = R.class), mediaType = "application/json") }) })
    @PostMapping("/{fileId}/delete")
    public Boolean deleteFile(@PathVariable("fileId") Long fileId) {
        return attachmentService.removeById(fileId);
    }

}
